import java.util.*;

public class sortInList {
    /**
     * 给定一个无序链表，要将其排序为升序链表
     * 思路: 将原链表从中间拆开，用递归方式将左右两部分分别排序，再合并
     *      用快慢指针的方式拆分
     * 
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head, pre = head, fast = head;
        while (fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        pre.next = null;

        return Merge(sortInList(head), sortInList(slow));
    }

    public ListNode Merge (ListNode pHead1, ListNode pHead2) {
        ListNode new_head = new ListNode(-1);
        ListNode cur = new_head;
        while (pHead1 != null && pHead2 != null) {
            if (pHead1.val < pHead2.val) {
                cur.next = pHead1;
                pHead1 = pHead1.next;
            } else {
                cur.next = pHead2;
                pHead2 = pHead2.next;
            }
            cur = cur.next;
        }
        if (pHead1 != null) {
            cur.next = pHead1;
        }
        if (pHead2 != null) {
            cur.next = pHead2;
        }
        return new_head.next;
    }
}